<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- <PageTools /> -->
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100%" alt="">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- <el-pagination layout="prev, pager, next" /> -->
          <el-pagination
            :current-page="pagePrams.page"
            :page-sizes="[5, 10, 20, 30]"
            :page-size="pagePrams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 实现新增的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees @success="hSuccess" />
      </el-dialog>

      <!-- 分配角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="showAssign">
        <assignRole
          v-if="showAssign"
          :cur-id="curId"
          @success="showAssign=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import addEmployees from './empDialog.vue'
import PageTools from '@/components/PageTools'
import { getEmployees, delEmployees } from '@/api/employees'
import Enum from '@/constant/employees'
import assignRole from './assignRole.vue'
// import addorEdit from './empDialog'

// const hireType = {}
// Enum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = Enum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    'PageTools': PageTools,
    addEmployees,
    assignRole

  },
  data() {
    return {
      curId: '',
      showAssign: false,
      list: [],
      pagePrams: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssign(id) {
      this.showAssign = true
      this.curId = id
    },
    exportExcel() {
      const { tHeader, data } = this.transZhKeyToExcel(this.list)
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        // const data = [[1, '三体', '刘慈欣', 100000, '2022-11-05'], [2, '西游记', '吴承恩', 100000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // header =  ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      // 1. 获取表头
      const one = list[0]

      if (!one) return

      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })

      // 2. 将每一个对象对象中的值存到一个数组中 ，将每个数组存储到大数组中
      const data = list.map(item => {
        //   console.log(' Object.values(item)', Object.values(item));
        return Object.values(item)
      })
      // console.log(headers);
      // console.log(data);

      return { tHeader, data }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 做删除
        const res = await delEmployees(id)
        console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
          this.loadEmployees()
        }
      }).catch(() => {

      })
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.pagePrams.size)
      this.pagePrams.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagePrams.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pagePrams.page = val
      this.loadEmployees()
    },
    formatEmployment(id) {
      // 从hireType中 通过id找到对应的元素的value
      return hireType[id] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees(this.pagePrams)
        console.log(res, 'getEmployees')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    }
  }
}
</script>
